import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import TablePage from "@/components/TablePage/TablePage";
import MusicSongBranchService from "./index.service";
import JsonPreview from "@/components/JsonPreview/JsonPreview";
import { useRouter } from "vue-router";
import to from "await-to-js";
import { message } from "ant-design-vue";
import styles from "./index.module.less";
import eventBus from "@/common/eventBus/mitt";
import Resubmit from "./Resubmit/Resubmit";
const StatusSwitch = defineComponent({
  props: {
    record: {
      type: Object,
    },
    value: {
      type: Number,
    }
  },
  emits: ["change"],
  setup(props: any, { emit }) {
    const musicSongBranchService = new MusicSongBranchService();
    const loading = ref(false);
    const statusChange = async (e) => {
      loading.value = true;
      const [err, res]: any = await to(musicSongBranchService.statusChange({
        record: props.record,
        status: e,
      }));
      if (!err) {
        e === 0 ? message.success("上架成功!") : message.success("下架成功!");
        emit("change");
      }
      loading.value = false;
    }
    return () => <a-switch loading={loading.value} checked={props.value} checkedValue={0} unCheckedValue={1} onChange={(e) => { statusChange(e) }} />
  }
})
export default defineComponent({
  name: "Branch",
  setup() {
    const router = useRouter();
    const tablePageRef = ref(null as any);
    const musicSongBranchService = new MusicSongBranchService();
    // 表格定义
    const tables = reactive({
      list: [
        {
          title: "伴奏支体管理",
          rowKey: "id",
          columns: [
            {
              title: "ID",
              dataIndex: "id",
              align: "center",
              width: "80px",
            },
            {
              title: "伴奏支体名称",
              dataIndex: "name",
              align: "center",
              width: "280px",
            },
            {
              title: "伴奏支体图片",
              dataIndex: "poster",
              align: "center",
              width: "280px",
            },
            {
              title: "伴奏支体内容",
              dataIndex: "content",
              align: "center",
              width: "180px",
            },
            {
              title: "伴奏支体内容(二四拍)",
              dataIndex: "contentTwoFour",
              align: "center",
              width: "180px",
            },
            {
              title: "mid文件",
              dataIndex: "midFile",
              align: "center",
              width: "280px",
            },
            {
              title: "排序",
              dataIndex: "sort",
              align: "center",
              width: "180px",
            },
            {
              title: "状态",
              dataIndex: "status",
              align: "center",
              width: "120px",
            },
            {
              title: "创建时间",
              dataIndex: "createTime",
              align: "center",
              width: "180px",
            },
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter", "search"],
            add: {
              permissions: "music:songBranch:add",
              handler: () => {
                router.push(`/musicScore/branchModify`);
              }
            },
          },
          searchForm: {
            name: {
              type: "input",
              label: "名称",
              attrs: { placeholder: "伴奏支体名称", allowClear: true },
            },
            status: {
              type: "select",
              label: "状态",
              attrs: { placeholder: "状态", allowClear: true },
              datas: [{ label: "开启", value: 0 }, { label: "关闭", value: 1 }],
            },
          },
          service: musicSongBranchService,
          operation: ({ record }) => [
            {
              type: "edit",
              permissions: "music:songBranch:edit",
              clickHandler: () => {
                router.push(`/musicScore/branchModify?id=${record.id}`);
              }
            },
            {
              type: "edit",
              text: "重传支体",
              permissions: "music:songBranch:edit",
              clickHandler: () => {
                const resubmitRef = tablePageRef.value.getPopup("resubmitRef");
                resubmitRef.value.open(record);
              }
            },
            {
              type: "delete",
              permissions: "music:songBranch:remove",
              clickHandler: "delete",
            },
          ],
          bodyCell: ({ text, record, index, column }) => {
            if (column.dataIndex === "poster") {
              return <>
                <a-image
                  width={120}
                  src={text}
                />
              </>
            }
            if (column.dataIndex === "status") {
              return <>
                <StatusSwitch record={record} value={Number(text)} />
              </>
            }
            if (column.dataIndex === "content") {
              return <a-button size="small" type="primary" onClick={() => { showJson(text, "伴奏支体内容") }}>查看</a-button>
            }
            if (column.dataIndex === "contentTwoFour") {
              return <a-button size="small" type="primary" onClick={() => { showJson(text, "伴奏支体(二四拍)内容") }}>查看</a-button>
            }
            if (column.dataIndex === "midFile") {
              return text ? <div class={styles.fileUrl} onClick={() => { downLoadUrl(text, '.mid', record) }}>{text}</div> : <span class={styles.noFile}>暂未上传mid文件</span>
            }
          },
          popups: [
            {
              ref: "jsonPreviewRef",
              dom: () => <JsonPreview />,
            },
            {
              ref: "resubmitRef",
              dom: () => <Resubmit onSuccess={() => {tablePageRef.value.reload()}}/>,
            },
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    })
    // 配置项
    const config = reactive({
      table: tables.list[0],
    })
    const showJson = (jsonStr: string, title: string) => {
      const jsonPreviewRef = tablePageRef.value.getPopup("jsonPreviewRef");
      jsonPreviewRef.value.open({
        title,
        jsonStr,
      });
    }
    // 下载文件
    const downLoadUrl = async (url: string, fileExtension: string, record: any) => {
      window.open(url);
    }
    onMounted(() => {
      eventBus.branchModifyFinish.on(() => {
        tablePageRef.value.reload();
      });
    })
    onUnmounted(() => {
      eventBus.branchModifyFinish.off();
    })
    return () => (
      <TablePage ref={tablePageRef} config={config} />
    )
  }
})